package com.library.controller.admin;


import com.library.commen.properties.JwtProperties;
import com.library.commen.utils.JwtUtil;
import com.library.pojo.Admin;
import com.library.pojo.Result;
import com.library.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController("adminLogin")
@Slf4j
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin){
        log.info("管理员{}登录",admin.getUserName());
        Admin admin1 = loginService.login(admin);
        if(admin1 != null) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", admin1.getId());
            claims.put("name", admin1.getUserName());
            String jwt = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
            return Result.success(jwt);
        }
        return Result.error("登陆失败，用户名或密码错误");
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }


}
